package com.csw.compose.ui


import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.DrawerState
import androidx.compose.material3.DrawerValue.Closed
import androidx.compose.material3.DrawerValue.Open
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.csw.compose.theme.AppTheme
import com.csw.compose.theme.pagePadding
import com.csw.compose.ui.components.CenterTitleWithMenu
import com.csw.compose.ui.module.BasePage
import com.csw.compose.ui.module.animation.ComponentAnimationPage
import com.csw.compose.ui.module.animation.ComponentAnimationPageData
import com.csw.compose.ui.module.animation.ContentSwitchAnimationPage
import com.csw.compose.ui.module.animation.ContentSwitchAnimationPageData
import com.csw.compose.ui.module.animation.MultiAnimationPage
import com.csw.compose.ui.module.animation.MultiAnimationPageData
import com.csw.compose.ui.module.animation.VisibilityAnimationPage
import com.csw.compose.ui.module.animation.VisibilityAnimationPageData
import com.csw.compose.ui.module.compatible.ViewComposePage
import com.csw.compose.ui.module.compatible.ViewComposePageData
import com.csw.compose.ui.module.component.ModifierData
import com.csw.compose.ui.module.component.ModifierPage
import com.csw.compose.ui.module.component.advanced.BottomSheetPage
import com.csw.compose.ui.module.component.advanced.BottomSheetPageData
import com.csw.compose.ui.module.component.advanced.ChipPage
import com.csw.compose.ui.module.component.advanced.ChipPageData
import com.csw.compose.ui.module.component.advanced.DatePickerPage
import com.csw.compose.ui.module.component.advanced.DatePickerPageData
import com.csw.compose.ui.module.component.advanced.DialogPage
import com.csw.compose.ui.module.component.advanced.DialogPageData
import com.csw.compose.ui.module.component.advanced.DrawerPage
import com.csw.compose.ui.module.component.advanced.DrawerPageData
import com.csw.compose.ui.module.component.advanced.DropdownMenuPage
import com.csw.compose.ui.module.component.advanced.DropdownMenuPageData
import com.csw.compose.ui.module.component.advanced.NavigationData
import com.csw.compose.ui.module.component.advanced.NavigationPage
import com.csw.compose.ui.module.component.advanced.PullToRefreshPage
import com.csw.compose.ui.module.component.advanced.PullToRefreshPageData
import com.csw.compose.ui.module.component.advanced.ScaffoldPage
import com.csw.compose.ui.module.component.advanced.ScaffoldPageData
import com.csw.compose.ui.module.component.advanced.SegmentedButtonPage
import com.csw.compose.ui.module.component.advanced.SegmentedButtonPageData
import com.csw.compose.ui.module.component.advanced.TimePickerPage
import com.csw.compose.ui.module.component.advanced.TimePickerPageData
import com.csw.compose.ui.module.component.base.BadgePage
import com.csw.compose.ui.module.component.base.BadgePageData
import com.csw.compose.ui.module.component.base.ButtonPage
import com.csw.compose.ui.module.component.base.ButtonPageData
import com.csw.compose.ui.module.component.base.CheckBoxPage
import com.csw.compose.ui.module.component.base.CheckBoxPageData
import com.csw.compose.ui.module.component.base.DividerPage
import com.csw.compose.ui.module.component.base.DividerPageData
import com.csw.compose.ui.module.component.base.ProgressIndicatorPage
import com.csw.compose.ui.module.component.base.ProgressIndicatorPageData
import com.csw.compose.ui.module.component.base.RadioButtonPage
import com.csw.compose.ui.module.component.base.RadioButtonPageData
import com.csw.compose.ui.module.component.base.SliderPage
import com.csw.compose.ui.module.component.base.SliderPageData
import com.csw.compose.ui.module.component.base.SwitchPage
import com.csw.compose.ui.module.component.base.SwitchPageData
import com.csw.compose.ui.module.component.base.TextFieldPage
import com.csw.compose.ui.module.component.base.TextFieldPageData
import com.csw.compose.ui.module.component.base.TextPage
import com.csw.compose.ui.module.component.base.TextPageData
import com.csw.compose.ui.module.component.container.BoxData
import com.csw.compose.ui.module.component.container.BoxPage
import com.csw.compose.ui.module.component.container.CardPage
import com.csw.compose.ui.module.component.container.CardPageData
import com.csw.compose.ui.module.component.container.ColumnData
import com.csw.compose.ui.module.component.container.ColumnPage
import com.csw.compose.ui.module.component.container.FlowData
import com.csw.compose.ui.module.component.container.FlowPage
import com.csw.compose.ui.module.component.container.GridPage
import com.csw.compose.ui.module.component.container.GridPageData
import com.csw.compose.ui.module.component.container.LazyListData
import com.csw.compose.ui.module.component.container.LazyListPage
import com.csw.compose.ui.module.component.container.PagerData
import com.csw.compose.ui.module.component.container.PagerPage
import com.csw.compose.ui.module.component.container.RowData
import com.csw.compose.ui.module.component.container.RowPage
import com.csw.compose.ui.module.component.custom.CustomDrawPage
import com.csw.compose.ui.module.component.custom.CustomDrawPageData
import com.csw.compose.ui.module.component.custom.CustomLayoutPage
import com.csw.compose.ui.module.component.custom.CustomLayoutPageData
import com.csw.compose.ui.module.state.EffectPage
import com.csw.compose.ui.module.state.EffectPageData
import com.csw.compose.ui.module.state.RememberPage
import com.csw.compose.ui.module.state.RememberPageData
import kotlinx.coroutines.launch

/**
 * 通过Navigation实现页面导航
 *
 * [参考](https://developer.android.google.cn/codelabs/jetpack-compose-navigation?hl=zh_cn#0)
 */
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 屏幕延伸到系统UI之下，默认系统状态栏会变成透明背景
        enableEdgeToEdge()
        // Activity包扩展的setContent方法，可以直接设置Compose组件为页面显示的内容
        // 内部使用ComposeView作为页面视图，它用于View桥接Compose组件
        setContent {
            val drawerState = rememberDrawerState(initialValue = Closed)
            MainDrawer(drawerState) { MainContent(drawerState) }
        }
    }

    @Preview
    @Composable
    fun DrawerPreview() {
        MainDrawer(rememberDrawerState(initialValue = Open)) {}
    }
}

/**
 * 主页面以drawer实现侧边导航
 *
 * @param drawerState drawer开启状态，抽出来用于预览drawer布局
 * @param content 主界面内容
 */
@Composable
fun MainDrawer(drawerState: DrawerState, content: @Composable (() -> Unit)) {
    // Compose组件采用声明式UI，最外层通常使用主题来设置全局样式，这里基于MaterialTheme组件自定义APP主题
    val mainViewModel: MainViewModel = viewModel()
    val moduleList = remember { mainViewModel.moduleList }
    val selectedModule = remember { mainViewModel.selectedModule }
    val scope = rememberCoroutineScope()
    AppTheme {
        ModalNavigationDrawer(
            drawerState = drawerState,
            drawerContent = {
                // Drawer抽屉组件，内部通过Modifier.windowInsetsPadding避开了顶部和左侧的窗口边称
                // 并且设置了默认样式
                ModalDrawerSheet(
                    modifier = Modifier.width(250.dp),
                ) {
                    Column(Modifier.padding(10.dp)) {
                        Text(
                            "模块列表",
                            style = MaterialTheme.typography.titleLarge,
                            textAlign = TextAlign.Center,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 10.dp)
                        )
                        moduleList.forEach { module ->
                            NavigationDrawerItem(
                                { Text(module.title) },
                                selected = module === selectedModule.value,
                                onClick = {
                                    mainViewModel.selectedModule.value = module
                                    scope.launch {
                                        drawerState.close()
                                    }
                                }
                            )
                        }
                    }
                }
            },
            content = content,
        )
    }
}

/**
 * 主界面内容
 */
@Composable
fun MainContent(drawerState: DrawerState) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
            .padding(pagePadding)
    ) {
        // 由于UI布局到了状态栏之下，这里通过获取顶部边称区作为高度，设置一个透明占位，防止页面
        // 内容入侵状态栏
//        Spacer(Modifier.windowInsetsTopHeight(WindowInsets.statusBars))
        val navController = rememberNavController()
        val scope = rememberCoroutineScope()
        val openDrawer: (() -> Unit) = {
            scope.launch {
                drawerState.open()
            }
        }
        val mainViewModel: MainViewModel = viewModel()
        val moduleList = remember { mainViewModel.moduleList }
        val selectedModule = remember { mainViewModel.selectedModule }
        // NavHost貌似会导致预览失效，目前还不知道怎么搞，所以先抽出来不预览。。。
        NavHost(navController, startDestination = Main.route) {
            composable(Main.route) {
                Column {
                    CenterTitleWithMenu(selectedModule.value.title, openDrawer)
                    Column(Modifier.verticalScroll(rememberScrollState())) {
                        selectedModule.value.pages.forEach {
                            Button(onClick = {
                                navController.navigate(it.jump)
                            }) {
                                Text(it.title)
                            }
                        }
                    }
                }
            }
            moduleList.forEach { moduleInfo ->
                moduleInfo.pages.forEach { pageInfo ->
                    composable(pageInfo.route) {
                        BasePage(navController::popBackStack, pageInfo.title, pageInfo.page)
                    }
                }
            }
        }
    }
}

class Main {
    companion object : Destination("Main")
}

class ModuleInfo(
    val title: String,
    val pages: List<PageInfo>
)

class PageInfo(
    val title: String,
    val route: String,
    val jump: String,
    val page: @Composable () -> Unit
)

class MainViewModel : ViewModel() {
    val moduleList = mutableStateListOf(
        ModuleInfo(
            "基础组件",
            listOf(
                PageInfo(
                    "修饰符",
                    ModifierData.route,
                    ModifierData.getRouteWithParams()
                ) { ModifierPage() },
                PageInfo(
                    "文本（Text）",
                    TextPageData.route,
                    TextPageData.getRouteWithParams()
                ) { TextPage() },
                PageInfo(
                    "文本输入（TextField）",
                    TextFieldPageData.route,
                    TextFieldPageData.getRouteWithParams()
                ) { TextFieldPage() },
                PageInfo(
                    "按钮（Button）",
                    ButtonPageData.route,
                    ButtonPageData.getRouteWithParams()
                ) { ButtonPage() },
                PageInfo(
                    "复选框（CheckBox）",
                    CheckBoxPageData.route,
                    CheckBoxPageData.getRouteWithParams()
                ) { CheckBoxPage() },
                PageInfo(
                    "单选按钮（RadioButton）",
                    RadioButtonPageData.route,
                    RadioButtonPageData.getRouteWithParams()
                ) { RadioButtonPage() },
                PageInfo(
                    "进度条（ProgressIndicator）",
                    ProgressIndicatorPageData.route,
                    ProgressIndicatorPageData.getRouteWithParams()
                ) { ProgressIndicatorPage() },
                PageInfo(
                    "滑块（Slider）",
                    SliderPageData.route,
                    SliderPageData.getRouteWithParams()
                ) { SliderPage() },
                PageInfo(
                    "开关（Switch）",
                    SwitchPageData.route,
                    SwitchPageData.getRouteWithParams()
                ) { SwitchPage() },
                PageInfo(
                    "分隔线（Divider）",
                    DividerPageData.route,
                    DividerPageData.getRouteWithParams()
                ) { DividerPage() },
                PageInfo(
                    "徽章（BadgeBox）",
                    BadgePageData.route,
                    BadgePageData.getRouteWithParams()
                ) { BadgePage() },
            )
        ),
        ModuleInfo(
            "容器组件",
            listOf(
                PageInfo(
                    "盒子组件（Box）",
                    BoxData.route,
                    BoxData.getRouteWithParams()
                ) { BoxPage() },
                PageInfo(
                    "行组件（Row）",
                    RowData.route,
                    RowData.getRouteWithParams()
                ) { RowPage() },
                PageInfo(
                    "列组件（Column）",
                    ColumnData.route,
                    ColumnData.getRouteWithParams()
                ) { ColumnPage() },
                PageInfo(
                    "分页组件（Pager）",
                    PagerData.route,
                    PagerData.getRouteWithParams()
                ) { PagerPage() },
                PageInfo(
                    "流式布局组件（Flow）",
                    FlowData.route,
                    FlowData.getRouteWithParams()
                ) { FlowPage() },
                PageInfo(
                    "列表组件（LazyList）",
                    LazyListData.route,
                    LazyListData.getRouteWithParams()
                ) { LazyListPage() },
                PageInfo(
                    "卡片（Card）",
                    CardPageData.route,
                    CardPageData.getRouteWithParams()
                ) { CardPage() },
                PageInfo(
                    "网格列表（Grid）",
                    GridPageData.route,
                    GridPageData.getRouteWithParams()
                ) { GridPage() },
            )
        ),
        ModuleInfo(
            "高级组件",
            listOf(
                PageInfo(
                    "脚手架（Scaffold）",
                    ScaffoldPageData.route,
                    ScaffoldPageData.getRouteWithParams()
                ) { ScaffoldPage() },
                PageInfo(
                    "页面导航",
                    NavigationData.route,
                    NavigationData.getRouteWithParams()
                ) { NavigationPage() },
                PageInfo(
                    "底部抽屉（ModalBottomSheet）",
                    BottomSheetPageData.route,
                    BottomSheetPageData.getRouteWithParams()
                ) { BottomSheetPage() },
                PageInfo(
                    "条状标签（Chip）",
                    ChipPageData.route,
                    ChipPageData.getRouteWithParams()
                ) { ChipPage() },
                PageInfo(
                    "日期选择器（DatePicker）",
                    DatePickerPageData.route,
                    DatePickerPageData.getRouteWithParams()
                ) { DatePickerPage() },
                PageInfo(
                    "时间选择器（TimePicker）",
                    TimePickerPageData.route,
                    TimePickerPageData.getRouteWithParams()
                ) { TimePickerPage() },
                PageInfo(
                    "对话框（Dialog）",
                    DialogPageData.route,
                    DialogPageData.getRouteWithParams()
                ) { DialogPage() },
                PageInfo(
                    "弹窗（DropdownMenu）",
                    DropdownMenuPageData.route,
                    DropdownMenuPageData.getRouteWithParams()
                ) { DropdownMenuPage() },
                PageInfo(
                    "抽屉式导航栏（ModalNavigationDrawer）",
                    DrawerPageData.route,
                    DrawerPageData.getRouteWithParams()
                ) { DrawerPage() },
                PageInfo(
                    "下拉刷新（PullToRefresh）",
                    PullToRefreshPageData.route,
                    PullToRefreshPageData.getRouteWithParams()
                ) { PullToRefreshPage() },
                PageInfo(
                    "分段按钮（SegmentedButton）",
                    SegmentedButtonPageData.route,
                    SegmentedButtonPageData.getRouteWithParams()
                ) { SegmentedButtonPage() },
            )
        ),
        ModuleInfo(
            "自定义组件",
            listOf(
                PageInfo(
                    "自定义组件-绘制",
                    CustomDrawPageData.route,
                    CustomDrawPageData.getRouteWithParams()
                ) { CustomDrawPage() },
                PageInfo(
                    "自定义组件-布局",
                    CustomLayoutPageData.route,
                    CustomLayoutPageData.getRouteWithParams()
                ) { CustomLayoutPage() },
            )
        ),
        ModuleInfo(
            "兼容性",
            listOf(
                PageInfo(
                    "View Compose兼容",
                    ViewComposePageData.route,
                    ViewComposePageData.getRouteWithParams()
                ) { ViewComposePage() },
            )
        ),
        ModuleInfo(
            "动画",
            listOf(
                PageInfo(
                    "可见性动画",
                    VisibilityAnimationPageData.route,
                    VisibilityAnimationPageData.getRouteWithParams()
                ) { VisibilityAnimationPage() },
                PageInfo(
                    "内容切换动画",
                    ContentSwitchAnimationPageData.route,
                    ContentSwitchAnimationPageData.getRouteWithParams()
                ) { ContentSwitchAnimationPage() },
                PageInfo(
                    "组件动画",
                    ComponentAnimationPageData.route,
                    ComponentAnimationPageData.getRouteWithParams()
                ) { ComponentAnimationPage() },
                PageInfo(
                    "多动画",
                    MultiAnimationPageData.route,
                    MultiAnimationPageData.getRouteWithParams()
                ) { MultiAnimationPage() },
            )
        ),
        ModuleInfo(
            "状态管理",
            listOf(
                PageInfo(
                    "不受重组影响的变量（remember）",
                    RememberPageData.route,
                    RememberPageData.getRouteWithParams()
                ) { RememberPage() },
                PageInfo(
                    "附带效应（Effect）",
                    EffectPageData.route,
                    EffectPageData.getRouteWithParams()
                ) { EffectPage() },
            )
        ),
    )
    val selectedModule = mutableStateOf(moduleList.first())

}